package com.huan.seata.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huan.seata.entity.AccountDO;
import com.huan.seata.mapper.AccountMapper;
import com.huan.seata.service.AccountService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author huan.fu 2021/9/27 - 下午2:01
 */
@Service
@Slf4j
@AllArgsConstructor
public class AccountServiceImpl implements AccountService {
    
    private final AccountMapper accountMapper;
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    @DS("account")
    public void debit(Integer id, Long amount) {
        log.info("准备扣除用户id:[{}][{}]分钱.", id, amount);
        
        LambdaUpdateWrapper<AccountDO> wrapper = Wrappers.lambdaUpdate(AccountDO.class)
                .eq(AccountDO::getId, id)
                .gt(AccountDO::getBalance, 0)
                .setSql("balance = balance -" + amount);
        
        int result = accountMapper.update(null, wrapper);
        
        if (result <= 0) {
            throw new RuntimeException("余额不足");
        }
    }
}
